package com.baoming.web.action;

import com.baoming.container.ServiceContainer;
import com.baoming.domain.Properties;
import com.baoming.service.IPropertiesService;
import com.baoming.web.form.ValueForm;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class ProperyValueAction extends BaseAction implements ModelDriven<ValueForm>{

	private ValueForm values = new ValueForm() ; 
	private IPropertiesService propService = (IPropertiesService) ServiceContainer.getService(IPropertiesService.SERVICE) ; 
	
	/**
	 * 删除属性
	 */
	public String delete(){
		
		String propId = values.getPropId() ; 
		String value = values.getVal() ; 
		
		if(propId == null || value == null){
			return "delete" ; 
		}
		
		//查询出属性信息
		Properties prop = propService.selectPropById(propId) ;
		if(prop != null){
			//得到属性值 
			String propValue = prop.getXmlValue() ; 
			System.out.println("propValue = " + propValue);
			if(propValue != null){
				value+="," ;
				
				//把这个属性值 设置为空
				propValue  =  propValue.replaceFirst(value, "") ; 
	
				//设值
				prop.setXmlValue(propValue) ; 
				
				System.out.println("propValue2 = " + propValue);
				
				//更新操作
				propService.updateProp(prop);
			}
		}
		  
		return "delete" ; 
	}
	
	/**
	 * 保存属性的值 
	 * @return
	 */
	@Override
	public String add() {
		String propId = values.getPropId() ; 
		 
		//如果id 为空 则直接返回
		if(propId == null || "".equals(propId)){
			return SUCCESS ;
		}
		
		String[] vs = values.getValues() ; 
		String valueStr = "" ; 
		
		for(int i = 0 ; i < vs.length ; i ++){
			String value = vs[i] ; 
			
			//除去非法字符
			if(!value.contains(",")){ 
			   valueStr += (value+",") ;  
			} 
		}
		Properties prop = propService.selectPropById(propId) ; 
		
		//添加值
		if(prop.getXmlValue() != null){
			valueStr += prop.getXmlValue() ; 
		}
		
		//更新保存值到数据库中 
		propService.updateProp(valueStr,propId) ; 
		
		//传输propId到界面 
		request.setAttribute("propId", propId) ; 
		
		return "add" ; 
	}

	@Override
	public String edit() {
		return null;
	}

	@Override
	public String manager() {
		return null;
	}

	@Override
	public String remove() {
		return null;
	}

	@Override
	public String removeGroup() {
		return null;
	}

	public ValueForm getModel() {
		return values ;
	}

}
